package org.gitos.cloud.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gitos.cloud.domain.comm.BConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Optional;

/**
 * 类ContextKit.java的实现描述：处理session
 *
 * @author shizc 2015年7月14日 上午10:46:24
 */
@Component
public class ContextKit {

	private static final Logger log = LoggerFactory.getLogger(ContextKit.class);

	public static void setCookieAuth(HttpServletRequest request, HttpServletResponse response, JSession jsession) {
		CookieAuth cookieAuth = getCookieAuth(request);
		if (cookieAuth == null) {
			cookieAuth = new CookieAuth();
		}
		cookieAuth.setSessionKey(jsession.getGlobalSessionId());
		cookieAuth.setIp(WebKit.getIpAddr(request));
		cookieAuth.setTimeStamp(System.currentTimeMillis());
		cookieAuth.setUserAgent(request.getHeader("User-Agent"));

		String szCookieAuth = JSON.toJSONString(cookieAuth);
		String data = CommonKit.encryptAndBase64(szCookieAuth);
		// 设置cookieauth
		WebKit.addCookie(response, null, "/", true, BConstant.COOKIE_KEY, data, RedisHelper.getExpireTime());
		// 保存session
		RedisHelper.setJSession(jsession);
	}

	public static CookieAuth getCookieAuth(HttpServletRequest request) {
		String encodedData = WebKit.getCookieValueByName(request, BConstant.COOKIE_KEY);
		if (StringUtils.isEmpty(encodedData)) {
			return null;
		}
		String data = CommonKit.decodebase64AndDecrypt(encodedData);
		CookieAuth cookieAuth = JSON.parseObject(data, CookieAuth.class);
		return cookieAuth;
	}

	// public static Optional<JSession> getCurrentUser(String token) {
	// do {
	// JSession jsession = RedisHelper.getJSession(token);
	// if (jsession != null) {
	// RedisHelper.expire(token, RedisHelper.expireTime, TimeUnit.SECONDS);
	//
	// if (BConstant.isSingleton) {
	// String user_uuid = jsession.getAttribute(BConstant.JSESSION_USER_UUID);
	// if (RedisHelper.hasKey(user_uuid)) {
	// RedisHelper.expire(user_uuid, RedisHelper.expireTime, TimeUnit.SECONDS);
	// }
	// }
	//
	// }
	// return Optional.fromNullable(jsession);
	// } while (false);
	// }

	public static Optional<JSession> getJSession(HttpServletRequest request) {
		do {
			CookieAuth cookieAuth = getCookieAuth(request);
			if (cookieAuth == null) {
				log.warn("cookieAuth is null");
				break;
			}

			// 用户的session key
			if (StringUtils.isEmpty(cookieAuth.getSessionKey()) || cookieAuth.getSessionKey().length() != 32) {
				log.warn("cookie中securityKey不对:{}", cookieAuth.getSessionKey());
				break;
			}

			// 验证ip地址是否一致
			String rawIp = WebKit.getIpAddr(request);
			if (rawIp == null) {
				rawIp = "";
			}
			if (!rawIp.equalsIgnoreCase(cookieAuth.getIp())) {
				log.warn("和上次不是同一个ip, 拒绝登录cookie.ip:{}, raw.ip:{}", cookieAuth.getIp(), rawIp);
				break;
			}

			// 验证登录cookie时间是否有效
			if (cookieAuth.getTimeStamp() == null) {
				log.warn("登录cookie时间失效");
				break;
			}
			if (System.currentTimeMillis() > cookieAuth.getTimeStamp() + RedisHelper.getExpireTime() * 1000) {
				log.warn("登录cookie时间已经失效");
				break;
			}
			// 从redis获取用户jsession
			JSession jsession = RedisHelper.getJSession(cookieAuth.getSessionKey());
			return Optional.fromNullable(jsession);
		} while (false);
		return Optional.absent();

	}

}
